<?php
namespace Admin\Controller;

use Think\Controller;

/***
 * Class ChatApiController
 * @package Admin\Controller聊天客服信息
 */
class ChatApiController extends Controller{


    public function __construct()
    {
        //跨域权限
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
    }

    /***
     * @param:
     * @param:获取客服信息
     */
     public function get_kf(){

//         $id=46;
         $id=$_SESSION['id'];
         $is_kf=M('shopkeeper_role','','XYC')->where(['sid'=>$id])->getField('rid',true);
         $merchant=[];
         if(in_array('4',$is_kf)){
             $where['id']=$id;
             $merchant=M('shopkeeper','','XYC')->where($where)->field('shop_idenfier,picture,id,name,merchant_name,account,mobile,chan_id')->find();
             //是否购买了坐席
             $merchant['is_agent']=0;
             $is_agent=M('merchant_business_accont','','XYC')->where(['shop_identifier'=>$merchant['shop_idenfier'],'keeper_id'=>$id,'app_expire_time'=>['gt',time()]])->find();
             if(!empty($is_agent)){
                 $merchant['is_agent']=1;
             }
         }
         $this->ajaxReturn(array('code'=>'1001','result'=>$merchant));
     }

    /***
     * @param:
     * @param:获取客服信息
     */
    public function get_kf_test(){

         $id=111;
//        $id=$_SESSION['id'];
        $is_kf=M('shopkeeper_role','','XYC')->where(['sid'=>$id])->getField('rid',true);
        $merchant=[];
        if(in_array('4',$is_kf)){
            $where['id']=$id;
            $merchant=M('shopkeeper','','XYC')->where($where)->field('shop_idenfier,picture,id,name,merchant_name,account,mobile,chan_id')->find();
            //是否购买了坐席
            $merchant['is_agent']=0;
            $is_agent=M('merchant_business_accont','','XYC')->where(['shop_identifier'=>$merchant['shop_idenfier'],'keeper_id'=>$id,'app_expire_time'=>['gt',time()]])->find();
            if(!empty($is_agent)){
                $merchant['is_agent']=1;
            }
        }
        $this->ajaxReturn(array('code'=>'1001','result'=>$merchant));
    }


    /***
     * 语音验证码接口
     */
    public function voice_code(){
        $phone = I('phone');
        $code = I('code');
        $times = date('YmdHis', time());
        $accountID = 'N00000020241';
        $APISecret = 'b9e14b50-2d7a-11e8-970c-995458c2f812';
        $number = $accountID . $APISecret . $times;
        $sig_s = md5($number);
        $sig = strtoupper($sig_s);
        $url = 'http://apis.7moor.com/v20160818/webCall/webCall/N00000020241?sig=' . $sig;
        $post_data = array('Action' => 'Webcall', 'Exten' => $phone, 'ServiceNo' => '01025270182','WebCallType'=>'asynchronous','Timeout'=>40,'MaxCallTime'=>60,'CallBackUrl'=>'http://xycshop.dstlkj.com/ChatApi/voice_call_back','CallBackType'=>'post','Variable'=>'message:您的验证码为  '.$code);
        $post_data = json_encode($post_data);
        $str = 'N00000020241:' . $times;
        $baseStr = base64_encode($str);
        $header = array("Accept:application/json", "Content-Type:application/json;charset=utf-8", "Content-Length:" . strlen($post_data), "Authorization:" . $baseStr);
        $ret = $this->http($url, $post_data, 1, $header);
        $result=json_decode($ret,true);
        //存表记录
        $add_arr=array('action_id'=>$result['ActionID'],'success'=>$result['Succeed'],'code'=>$code,'phone'=>$phone);
        M('voice_code_record','','XYC')->add($add_arr);

        if($result['Succeed']==true){
            $this->ajaxReturn(array('code'=>'1001','result'=>'已发送'));
        }else{
            $this->ajaxReturn(array('code'=>'1002','result'=>'发送失败'));
        }
    }

    /***
     * 语音验证码接口
     */
    public function voice_code1(){
        $phone = I('phone');
        $code = I('code');
        $times = date('YmdHis', time());
        $accountID = 'N00000020241';
        $APISecret = 'b9e14b50-2d7a-11e8-970c-995458c2f812';
        $number = $accountID . $APISecret . $times;
        $sig_s = md5($number);
        $sig = strtoupper($sig_s);
        $url = 'http://apis.7moor.com/v20160818/webCall/webCall/N00000020241?sig=' . $sig;
        $post_data = array('Action' => 'Webcall', 'Exten' => $phone, 'ServiceNo' => '01025270182','WebCallType'=>'asynchronous','Timeout'=>40,'MaxCallTime'=>60,'CallBackUrl'=>'http://xycshop.dstlkj.com/ChatApi/voice_call_back','CallBackType'=>'post','Variable'=>'message:您的验证码为  '.$code);
        $post_data = json_encode($post_data);
        $str = 'N00000020241:' . $times;
        $baseStr = base64_encode($str);
        $header = array("Accept:application/json", "Content-Type:application/json;charset=utf-8", "Content-Length:" . strlen($post_data), "Authorization:" . $baseStr);
        $ret = $this->http($url, $post_data, 1, $header);
        $result=json_decode($ret,true);
        //存表记录
        $add_arr=array('action_id'=>$result['ActionID'],'success'=>$result['Succeed'],'code'=>$code,'phone'=>$phone);
        M('voice_code_record','','XYC')->add($add_arr);
        var_dump($result);
        if($result['Succeed']==true){
            $this->ajaxReturn(array('code'=>'1001','result'=>'已发送'));
        }else{
            $this->ajaxReturn(array('code'=>'1002','result'=>'发送失败'));
        }
    }
    /***
     * 语音验证码接口
     */
    public function voice_tell(){
        if(!$_POST){
            $this->ajaxReturn(array('code'=>'1002','result'=>'请以POST访问!'));
            die;
        }
        $phone = I('phone');
        $content = I('flag');
        $times = date('YmdHis', time());
        $accountID = 'N00000020241';
        $APISecret = 'b9e14b50-2d7a-11e8-970c-995458c2f812';
        $number = $accountID . $APISecret . $times;
        $sig_s = md5($number);
        $sig = strtoupper($sig_s);
        $url = 'http://apis.7moor.com/v20160818/webCall/webCall/N00000020241?sig=' . $sig;
        $post_data = array('Action' => 'Webcall', 'Exten' => $phone, 'ServiceNo' => '01025270182','WebCallType'=>'asynchronous','Timeout'=>40,'MaxCallTime'=>60,'CallBackUrl'=>'http://xycshop.dstlkj.com/ChatApi/voice_call_back','CallBackType'=>'post','Variable'=>'message: 1,flag:'.$content);
        $post_data = json_encode($post_data);
        $str = 'N00000020241:' . $times;
        $baseStr = base64_encode($str);
        $header = array("Accept:application/json", "Content-Type:application/json;charset=utf-8", "Content-Length:" . strlen($post_data), "Authorization:" . $baseStr);
        $ret = $this->http($url, $post_data, 1, $header);
        $result=json_decode($ret,true);
        //存表记录

        $add_arr=array('action_id'=>$result['ActionID'],'success'=>$result['Succeed'],'code'=>$content,'phone'=>$phone);
        M('voice_code_record','','XYC')->add($add_arr);
        if($result['Succeed']==true){
            $this->ajaxReturn(array('code'=>'1001','result'=>'已发送'));
        }else{
            $this->ajaxReturn(array('code'=>'1002','result'=>'发送失败'));
        }
    }


    /**
     * 语音外呼回调
     */
    public function voice_call_back(){

        $actionid=I('actionid');
        $Message=I('Message');
        M('voice_code_record','','XYC')->where(['action_id'=>$actionid])->setField('msg',$Message);

    }

     /***
      * 语音外呼
      */
     public function voice_call(){

         $times = date('YmdHis', time());
//         $phone = I('phone');
         $accountID = 'N00000020241';
         $APISecret = 'b9e14b50-2d7a-11e8-970c-995458c2f812';
         $number = $accountID . $APISecret . $times;
         $sig_s = md5($number);
         $sig = strtoupper($sig_s);
         $url = 'http://apis.7moor.com/v20160818/webCall/webCall/N00000020241?sig=' . $sig;
         $post_data = array('Action' => 'Webcall', 'Exten' => 13758792879, 'ServiceNo' => '01025270182','CallBackType'=>'post','Variable'=>'message:您的验证码为123456789 ');
         $post_data = json_encode($post_data);
         $str = 'N00000020241:' . $times;
         $baseStr = base64_encode($str);
         $header = array("Accept:application/json", "Content-Type:application/json;charset=utf-8", "Content-Length:" . strlen($post_data), "Authorization:" . $baseStr);
         $ret = $this->http($url, $post_data, 1, $header);
         var_dump($ret);
     }

     public function call_code(){
         $url='http://115.29.14.183:3000/OpenService?action=voiceVerifyStandard&account=N00000020241&exten=13758792879&verifyCode=123456';
//         $post_data = array('action' => , 'account' => 'N00000020241', 'exten' => '13758792879','verifyCode'=>'123456');
//         $post_data = json_encode($post_data);
         $ret = $this->http($url,'',0);
         var_dump($ret);
     }

    /**
     * 7天真删除
     */
    public function del_user_real(){
        $seven_day=time()-7*24*3600;
        $where['d_time']=['lt',$seven_day];
        $where['is_delete']=['eq',-1];
        $del_users=M('user','','XYC')->where($where)->Field('id,shop_identifier')->select();
        $ids=array_column($del_users,'id');
        var_dump($ids);
        M('user','','XYC')->where(['id'=>['in',$ids]])->delete();
        M('user_login','','XYC')->where(['user_id'=>['in',$ids]])->delete();
        foreach ($del_users as $k=>$v){
            add_control_log($v['shop_identifier'],'系统','7天真删除用户'.$v['id'],3);
        }
    }
    /**
     * http请求
     * @param  string $url 请求地址
     * @param  boolean|string|array $params 请求数据
     * @param  integer $ispost 0/1，是否post
     * @param  array $header
     * @param  $verify 是否验证ssl
     * return string|boolean          出错时返回false
     */
    function http($url, $params, $ispost = 1, $header = [], $verify = false)
    {
        $httpInfo = array();
        $ch = curl_init();
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        //忽略ssl证书
        if ($verify === true) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if (is_array($params)) {
                $params = http_build_query($params);
            }
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            trace("cURL Error: " . curl_errno($ch) . ',' . curl_error($ch), 'error');
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
            trace($httpInfo, 'error');
            return false;
        }
        curl_close($ch);
        return $response;
    }


}